package constant.milk.cashbook.sms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.MemoActivity;
import constant.milk.cashbook.asset.MoneyActivity;
import constant.milk.cashbook.bean.BankData;
import constant.milk.cashbook.bean.CheckData;
import constant.milk.cashbook.bean.CreditData;
import constant.milk.cashbook.bean.GiftData;
import constant.milk.cashbook.bean.PhoneData;
import constant.milk.cashbook.bean.RealData;
import constant.milk.cashbook.bean.SmsData;
import constant.milk.cashbook.bean.SmsInputData;
import constant.milk.cashbook.category.CategoryMainListActivity;
import constant.milk.cashbook.category.CategorySubListActivity;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.insert.AssetChoiceActivity;
import constant.milk.cashbook.insert.AssetListActivity;
import constant.milk.cashbook.insert.InsertActivity;
import constant.milk.cashbook.sms.parser.SmsParser;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.CalendarActivity;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkUtil;
import constant.milk.cashbook.util.TimeActivity;

public class SmsAssayActivity extends SuperActivity
{
	public static final int ASSET_CHOICE_REQUEST_CODE = 0;
	public static final int ASSET_LIST_REQUEST_CODE = 1;
	public static final int REALMONEY_LIST_REQUEST_CODE = 2;
	
	public static final String SMS_MESSAGE = "SMS_MESSAGE";
	public static final String SMS_ADDRESS = "SMS_ADDRESS";
	
	private TextView typeTextView;
	private TextView telTextView;
	private TextView assetTextView;
	private TextView moneyTextView;
	private TextView memoTextView;
	
	private View linkAssetView;
	private TextView linkAssetTextView;
	
	private View linkAssetNameView;
	private TextView linkAssetNameTextView;
	
	private View realMoneyNameView;
	private TextView realMoneyNameTextView;
	
	private Button saveButton;
	
	private ArrayList<String> assetNameList;
	private ArrayList<String> realMoneyNameList;
	private ArrayList<SmsData> smsList;
	
	private MilkManager milkManager;
	
	private SmsParser parser;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sms_assay_activity);
		
		setTitle("문자분석");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		typeTextView = (TextView) findViewById(R.id.smsAssayTypeTextView);
		telTextView = (TextView) findViewById(R.id.smsAssayTelTextView);
		assetTextView = (TextView) findViewById(R.id.smsAssayAssetTextView);
		moneyTextView = (TextView) findViewById(R.id.smsAssayMoneyTextView);
		memoTextView = (TextView) findViewById(R.id.smsAssayMemoTextView);
		
		linkAssetView = findViewById(R.id.smsAssayLinkAssetView);
		linkAssetTextView = (TextView) findViewById(R.id.smsAssayLinkAssetTextView);
		
		linkAssetNameView = findViewById(R.id.smsAssayLinkAssetNameView);
		linkAssetNameTextView = (TextView) findViewById(R.id.smsAssayLinkAssetNameTextView);
		
		realMoneyNameView = findViewById(R.id.smsAssayRealMoneyNameView);
		realMoneyNameTextView = (TextView) findViewById(R.id.smsAssayRealMoneyNameTextView);
		
		saveButton = (Button) findViewById(R.id.saveButton);
	}

	@Override
	protected void setOnClick()
	{
		linkAssetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, SmsAssetActivity.class);
				intent.putExtra(SmsAssetActivity.ASSET_CHOICE_DATA, linkAssetTextView.getText().toString());
				startActivityForResult(intent, ASSET_CHOICE_REQUEST_CODE);
			}
		});
		
		linkAssetNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startAssetNameList();
			}
		});
		
		realMoneyNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startRealMoneyNameList();
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!checkInsert())
				{
					return;
				}
				
				if (setSaveData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 저장에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		try
		{
			DBSelectQuery select = new DBSelectQuery(superContext, superDb);
			milkManager = new MilkManager(superContext, superDb);
			
			Intent intent = getIntent();
			
			String address = intent.getStringExtra(SMS_ADDRESS);
			String message = intent.getStringExtra(SMS_MESSAGE);
			
			parser = new SmsParser(message);
			
			SmsInputData data = parser.messageParsing();
			
			if (data == null || parser.getAvailable() == false)
			{
				MilkUtil.showToast(superContext, "문자 분석에 실패 하였습니다. 문자 내용을 개발자에게 메일로 보내주세요.");
				finish();
			}
			
			if (parser.getSmsType() == SmsParser.HALBU_SMS)
			{
				MilkUtil.showToast(superContext, "할부 문자는 아직 지원하지 않습니다. 최대한 빨리 개발 하도록 하겠습니다.");
				finish();
			}
			
			String typeString = "";
			
			switch (parser.getSmsType())
			{
				case SmsParser.IN_SMS:
					typeString = "수입";
					realMoneyNameView.setVisibility(View.GONE);
					break;
				case SmsParser.OUT_SMS:
					typeString = "지출";
					realMoneyNameView.setVisibility(View.GONE);
					break;
				case SmsParser.IN_ATM_SMS:
					typeString = "이동";
					realMoneyNameView.setVisibility(View.VISIBLE);
					break;
				case SmsParser.OUT_ATM_SMS:
					typeString = "이동";
					realMoneyNameView.setVisibility(View.VISIBLE);
					break;
				default:
					break;
			}
			
			typeTextView.setText(typeString);
			telTextView.setText(address);
			assetTextView.setText(data.getName());
			moneyTextView.setText(MilkUtil.getWon(data.getMoney()));
			memoTextView.setText(data.getMemo1());
			
			linkAssetTextView.setText(getString(R.string.creditCardAsset));
			setAssetNameData(linkAssetTextView.getText().toString());
			
			setRealMoneyNameData();
			
			smsList = select.getSmsList();
		} catch (Exception e)
		{
//			MilkUtil.showToast(superContext, "문자 분석에 실패 하였습니다. "
//					+ "문자내용을 개발자(milkconstant@gmail.com)에게 보내주시면 최대한 빨리 처리해 드리겠습니다. 감사합니다.");
			finish();
		}
	}
	
	private boolean checkInsert()
	{
		if (linkAssetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해 주세요.");
			return false;
		}
		
		if (telTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "전화번호가 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (assetTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "분석이름이 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (moneyTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "분석금액이 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (memoTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "분석내용이 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (linkAssetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "연결 자산이 없습니다. 자산관리에서 자산을 추가해주세요.");
			return false;
		}
		
		if (realMoneyNameView.getVisibility() == View.VISIBLE)
		{
			if (realMoneyNameTextView.getText().toString().equals(""))
			{
				MilkUtil.showToast(superContext, "연결 현금이 없습니다. 자산관리에서 현금을 추가해주세요.");
				return false;
			}
		}
		
		for (int i = 0; i < smsList.size(); i++)
		{
			SmsData data = smsList.get(i);
			
			if (data.getName().equals(assetTextView.getText().toString()))
			{
				MilkUtil.showToast(superContext, "이미 등록된 문자 입니다.");
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setSaveData()
	{
		DbInsertQuery query = null;
		
		try
		{
			query = new DbInsertQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("address", telTextView.getText().toString());
			map.put("name", assetTextView.getText().toString());
			map.put("memo", memoTextView.getText().toString());
			
			if (parser.getSmsType() == SmsParser.OUT_ATM_SMS)
			{
				map.put("cardname", realMoneyNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(getString(R.string.realAsset)));
				map.put("subcardname", linkAssetNameTextView.getText().toString());
				map.put("subasset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("type", SmsParser.IN_ATM_SMS + "");
			}
			else if (parser.getSmsType() == SmsParser.IN_ATM_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("subcardname", realMoneyNameTextView.getText().toString());
				map.put("subasset", milkManager.getAssetStr(getString(R.string.realAsset)));
				map.put("type", SmsParser.OUT_ATM_SMS + "");
			}
			else if (parser.getSmsType() == SmsParser.OUT_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("type", SmsParser.OUT_SMS + "");
			}
			else if (parser.getSmsType() == SmsParser.IN_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("type", SmsParser.IN_SMS + "");
			}
			
			query.setSms(map);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private void startAssetNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, linkAssetNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, linkAssetTextView.getText().toString());
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void startRealMoneyNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, realMoneyNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, getString(R.string.realAsset));
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void setAssetNameData(String str)
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		assetNameList = new ArrayList<String>();
		
		if (str.equals(getString(R.string.realAsset)))
		{
			ArrayList<RealData> list = query.getRealList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("현금을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.bankAsset)))
		{
			ArrayList<BankData> list = query.getBankList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("통장을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.checkCardAsset)))
		{
			ArrayList<CheckData> list = query.getCheckList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("체크카드를 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.creditCardAsset)))
		{
			ArrayList<CreditData> list = query.getCreditList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("신용카드를 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.phoneAsset)))
		{
			ArrayList<PhoneData> list = query.getPhoneList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("핸드폰을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.giftCardAsset)))
		{
			ArrayList<GiftData> list = query.getGiftList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("상품권을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
	}
	
	private void setRealMoneyNameData()
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		realMoneyNameList = new ArrayList<String>();
		
		ArrayList<RealData> list = query.getRealList();
		
		if (list == null || list.size() < 1)
		{
			realMoneyNameTextView.setText("");
			realMoneyNameTextView.setHint("현금을 추가해주세요.");
			return;
		}
		
		realMoneyNameTextView.setText(list.get(0).getName());
		
		for (int i = 0; i < list.size(); i++)
		{
			realMoneyNameList.add(list.get(i).getName());
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == ASSET_CHOICE_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetChoiceActivity.ASSET_CHOICE_DATA);
			linkAssetTextView.setText(str);
			
			setAssetNameData(str);
			
		}
		else if (requestCode == ASSET_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			linkAssetNameTextView.setText(str);
		}
		else if (requestCode == REALMONEY_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			realMoneyNameTextView.setText(str);
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_AUTO_SMS_ASSAY);
		startActivity(intent);
	}

}
